import axios from '@/common/axios'
// import qs from 'qs';
import { getTokenUrl, refreshTokenUrl, getMeUrl, userLoginUrl } from "@/common/api/url.js"

export function getToken(username, password) {
  return axios({
    method: 'post',
    url: getTokenUrl,
    // data: qs.stringify({ "username": username, "password": password }),
    data: { "username": username, "password": password },
    headers: { "Content-Type": "application/x-www-form-urlencoded" }
  })
}

export function refreshToken() {
  const refresh_token = uni.getStorageSync('refresh_token')
  return axios({
    method: 'post',
    url: refreshTokenUrl,
    data: { grant_type: 'grant_type', refresh_token: refresh_token }
  })
}

export function getMe() {
  return axios({ method: 'get', url: getMeUrl, authType: true })
}

export function uploadImage(filePath) {
  return axios({
    method: 'post',
    url: '/test/fastdfs/upload',
    filePath: filePath,
    name: 'file',
    authType: true
  })
}

export function MultiuploadImage(files) {
  return axios({
    method: 'post',
    url: '/test/fastdfs/upload/multi',
    files: files,
    authType: true
  })
}

export function userLogin(userinfo) {
  return axios({
    method: 'post',
    url: userLoginUrl,
    data: userinfo
  })
}

export function wxAppLogin() {
  return new Promise((resolve, reject) => {
    uni.getUserProfile({
      desc: "完善会员资料",
      success: (res) => {
        let userInfo = res.userInfo
        uni.setStorageSync('userInfo', userInfo)
        uni.login({
          success: (res) => {
            let code = res.code
            if (code) {
              userInfo.code = code
              userLogin(userInfo).then(res => {
                resolve(res)
              })
            } else { reject({ message: res.errMsg }) }
          }
        })
      },
      fail() {
        uni.showModal({
          title: "警告",
          content: "您点击了拒绝授权",
          showCancel: false,
          confirmText: "确定"
        })
      }
    })
  })
}
